export class ArrayUtils {
  /**
   * 相等查找第一个替换
   * @param first
   * @param second
   * @param equals
   */
  static findSecondReplaceFirst(first: [], second: [], equals: (first, second) => boolean): any[] {
    const result = []
    first.forEach(f => {
      const find = second.find(s => equals(f, s))
      if (find) {
        result.push(find)
      } else {
        result.push(f)
      }
    })
    return result
  }

  /**
   * 相等查找多个替换
   * @param first
   * @param second
   * @param equals
   */
  static filterSecondReplaceFirst(first: [], second: [], equals: (first, second) => boolean): any[] {
    const result = []
    first.forEach(f => {
      const find = second.filter(s => equals(f, s))
      if (find.length > 0) {
        result.push(...find)
      } else {
        result.push(f)
      }
    })
    return result
  }

  /**
   * 并集
   * @param first
   * @param second
   * @param equals
   */
  static union(first: [], second: [], equals: (first, second) => boolean): any[] {
    const result = [...first]
    second.forEach(s => {
      const find = first.find(f => equals(f, s))
      if (!find) {
        result.push(s)
      }
    })
    return result
  }

  /**
   * 交集
   * @param first
   * @param second
   * @param equals
   */
  static intersection(first: [], second: [], equals: (first, second) => boolean): any[] {
    const result = []
    second.forEach(s => {
      const find = first.find(f => equals(f, s))
      if (find) {
        result.push(s)
      }
    })
    return result
  }

  /**
   * 去重
   * @param arr
   * @param callBack
   */
  static duplicateRemoval(arr: [], callBack: (i) => string): any[] {
    return arr.filter(filterDuplicates(callBack))
  }
}

/**
 * 数组去重
 * 数组.filter(filterDuplicates(i=>{
 *         return i 这里返回的一定是字符串用来判断是否已经存在
 *       }))
 * @param callBack
 * @returns {(function(*): (boolean))|*}
 */
export const filterDuplicates = (callBack) => {
  const has = []
  return i => {
    // @ts-ignore
    if (has.includes(callBack(i))) {
      return false
    } else {
      // @ts-ignore
      has.push(i)
      return true
    }
  }
}
